<template>
  <a-upload
    v-model="url"
    :action="imgAction"
    :headers="uploadImgHeader"
    :show-upload-list="false"
    :before-upload="beforeUpload"
    :data="data"
    list-type="picture-card"
    @change="handleImgChange"
    class="img-uploader">
    <img v-if="url" :src="url" />
    <div v-else>
      <a-icon :type="imgLoading ? 'loading' : 'plus'" />
    </div>
  </a-upload>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const token = Vue.ls.get(ACCESS_TOKEN)
export default {
  props: {
    url: {
      type: [String, Number],
      default: ''
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      imgAction: process.env.VUE_APP_API_BASE_URL + '/experiment/common/commonFile/upload',
      uploadImgHeader: {
        'Authorization': 'Bearer ' + token
      },
      imgLoading: false
    }
  },
  methods: {
    // 验证文件大小
    beforeUpload (file) {
      const isImage = file.type.indexOf('image') !== -1
      if (!isImage) {
        this.$message.error('只能上传图片!')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 5
      if (!isLt10M) {
        this.$message.error('文件大小不可超过 5MB!')
      }
      return isImage && isLt10M
    },
    handleImgChange (info) {
      if (info.file.status === 'uploading') {
        this.imgLoading = true
        this.updatedImgUrl(0)
        return
      }
      if (info.file.status === 'done') {
        this.imgLoading = false
        const { path, domain } = info.file.response.content
        this.updatedImgUrl(domain + path)
      }
      if (info.file.status === 'error') {
        this.imgLoading = false
        this.updatedImgUrl('')
        this.$message.error('上传失败，请重试!')
      }
    },
    updatedImgUrl (val) {
      this.$emit('updatedImgUrl', val)
    }
  }
}
</script>
<style>
  .img-uploader .ant-upload-select-picture-card,
  .img-uploader img {
    width: 300px;
    height: 200px;
  }
</style>
